let sys = wx.getSystemInfoSync()
sys.model = sys.model.split('<')[0].split('(')[0]
sys.model = sys.model.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、 ]/g, '')

var listener = {}

var width = sys.windowHeight
var width = sys.windowHeight
const app = getApp()
const myaudio = wx.createInnerAudioContext();
var init;
var intetimes;
Page({
  data: {
    millisecond: 0,
    src: '',
    isFlag: true,
    time:false,
    loadingShow: false,
    auth_layer_isShow: false,
    winW: sys.windowWidth,
    winH: sys.windowHeight,
    machine_id: '',
    canWidth: 0,
    canHeight: 0,
    circleLoading: false,
    loadingIndex: '0',
    titlename:'',

    ctxCanvasNode: '',
    qrCodeUrl: '',
    result_token: '',
    isExit: false,
    photo_configure: '',
    layer_bg: '',
    borderT: 0,
    borderL: 0,
    borderW: 0,
    borderH: 0,
    jqW: 0,
    jqH: 0,
    jqT: 0,
    jqL: 0,
    pixelRatio: sys.pixelRatio,
    froms: '',
    // 扫码参数配置 start
    frameW: sys.windowWidth,
    frameH: sys.windowHeight,
    platform: sys.platform, // android  ios
    showTakeBtn: false,
    // 扫码参数配置 end
    takePhotoAn: '',
    isplay: false,//是否播放
    code:'',
    state:false,
    msg:'',
    yfyindex:0,
  },
  onShow(options) {
   
    myaudio.src = app.globalData.the_host + '/image/sound/ScanSound.mp3'
  
    wx.setStorage({
      key: "cameraIsExit",
      data: "0"
    })
    this.onstart()
    this.setData({
      isExit: false,
      isFlag: true,
      src: '',
    })
  },
  onHide() {
    wx.setStorage({
      key: "cameraIsExit",
      data: "1"
    })
    this.setData({
      isExit: true,
      isFlag: true
    })
  },
//离开页面触发 
  onUnload() {
    this.onstop()
    clearInterval(intetimes);
    wx.setStorage({
      key: "cameraIsExit",
      data: "1"
    })
    this.setData({
      isExit: true,
      state: true
    })
  },
  creatBg() {
    let width = this.data.winW * 0.46;
    let height = width * (360 / 256);
    let left = (this.data.winW - width) / 2
    let top = (this.data.winH) / 2 - height

    let left1 = (this.data.winW - width) / 2
    let top1 = (this.data.winH) / 2 - height

    this.setData({
      borderT: top,
      borderL: left,
      borderW: width,
      borderH: width * (360 / 256),
      jqW: width,
      jqH: height,
      jqT: top1,
      jqL: left1,
    })
    if (getApp().globalData.cameraTemp) {
      this.setData({
        layer_bg: getApp().globalData.cameraTemp
      })
      return
    }
    let ctx = wx.createCanvasContext('scannerCanvas4');
    console.log(ctx)
    ctx.rect(0, 0, this.data.winW, this.data.winH + 105)
    ctx.setFillStyle('rgba(0,0,0,0.5)')
    ctx.fill()
    ctx.clearRect(left, top, width, width * (360 / 256));
    ctx.draw(true, () => {
     this.reloadDrawBG()
    })
  },
  reloadDrawBG() {
    wx.canvasToTempFilePath({
      canvasId: 'scannerCanvas4',
      success: (res) => {
        console.log(res.tempFilePath)
        wx.saveFile({
          tempFilePath: res.tempFilePath,
          success: (e) => {
            console.log(e)
            this.setData({
              layer_bg: e.savedFilePath
            })
          //  getApp().globalData.cameraTemp = e.savedFilePath
          },
          fail: (e) => {
            console.log(e, '11111')
          }
        })
      },
      fail: () => {
        this.reloadDrawBG()
      }
    })
  },
  onLoad(options) {
    console.log(sys)
    wx.getNetworkType({
      success: function (res) {
        if (res.networkType == "none") {
          wx.showModal({
            title: '提示',
            content: '没有网络连接,请检查您的网络设置',
            showCancel: false,
          })
        } else if (res.networkType == "2g" || res.networkType == "3g"){
          wx.showModal({
            title: '提示',
            content: '网络信号差…',
            showCancel: false,
          })
        } else if (res.networkType == "unknown"){
          wx.showModal({
            title: '提示',
            content: '未知的网络类型,请检查您的网络设置',
            showCancel: false,
          })
        }
      },
      fail: function (err) {
        wx.showModal({
          title: '提示',
          content: '访问错误',
          showCancel: false,
        })
      }
    })
    this.creatBg()
    this.setCanvasSizeMode()
    wx.setNavigationBarTitle({
      title: '拍照'
    })
    let system = wx.getSystemInfoSync()
    system.version = system.version.replace(/\./g, '')
    if (system.version < 705 && this.data.platform == 'android') {
      wx.showModal({
        title: '提示',
        content: '请升级至微信最新版本体验多图，未升级只能拍照',
        showCancel: false,
        success(res) {
        }
      })
    } else {
      this.onCameraGet()
    }
  },
  setCanvasSizeMode() {
    this.setData({
      canWidth: this.data.jqW,
      canHeight: this.data.jqH
    })
  },
  onCameraGet() { //扫码
    this.data.isFlag = true
    var context = wx.createCameraContext()
    var isFisrt = false
    listener = context.onCameraFrame((frame) => {
  
      if (!this.data.isFlag) {
        return
      }
      this.setData({
        frameW: frame.width,
        frameH: frame.height,
        time:true

      })
      wx.canvasPutImageData({
        canvasId: 'mycanvas',
        x: 0,
        y: 0,
        width: frame.width,
        heihgt: frame.height,
        data: new Uint8ClampedArray(frame.data),
        success: (res) => {
          let l = 0
          let t = 0
          let xw = frame.width * 0.46
          let xh = xw * (360 / 256)
          l = (frame.width - xw) / 2
          t = (frame.height) / 2 - xh
          //console.log('取图：'+xw, xh, 'frame:', frame.width, frame.height, 'window:', this.data.winW, this.data.winH)
          let titlename1 = `取图：` + xw + ',' + xh + 'frame:' + frame.width + ',' + frame.height + 'window:' + ',' + this.data.winW + ',' + this.data.winH;
          
          wx.canvasGetImageData({
            canvasId: 'mycanvas',
            x: l,
            y: t,
            width: xw,
            height: xh,
            success: (res) => {
              var arr = [];
              var uindex = 0;
              var x1 = res.data;
          
              var x2 = new Uint8Array(xw * xh);
              for (var a = 0; a < x1.length; a++) {
                
                var yu = (a + 1) % 4;
                if (yu != 0) {
                  arr[yu - 1] = x1[a];
                } else {
                  x2[uindex] = parseInt((arr[0] * 30 + arr[1] * 59 + arr[2] * 11) / 100)
                  uindex++
                }
              }
             
              //console.log(x2[0])
              var s = wx.arrayBufferToBase64(x2)
              // console.log(s)
                 this.setData({
                   returnList: x2[0]
                })
              
              if (x2[0]==0){
                this.setData({
                  isFlag: true
                })
              }else{
                this.okClick(s, parseInt(res.width))
              }
            },
            fail: (e) => {
              this.setData({
                isFlag: true
              })
              console.log(e, 243)
            }
          })

        },
        fail: (res) => {
          this.setData({
            isFlag: true
          })
          console.log(res, 249)
        }
      })

      this.data.isFlag = false
      // listener.stop()
    })
    setTimeout(() => {
      listener.start()
    }, 500);
   
    setTimeout(() => {
      if (!this.data.time) {
        wx.showToast({
          title: '手机版本过低',
          icon: 'success',
          duration: 3000,
          success: function () {
            setTimeout(function () {
              listener.stop()
              wx.switchTab({
                url: '../index/index'
              })
            }, 2000) //延迟时间 
          }
        })
      }
      //console.log('10秒了！'+this.data.time)
    }, 5000 );
    clearInterval(intetimes);
    intetimes = setInterval(function () {
      wx.showToast({
        title: '扫码超时',
        icon: 'success',
        duration: 3000,
        success: function () {
          setTimeout(function () {
            //this.data.cameraListener.stop()
            clearInterval(intetimes);
            wx.switchTab({
              url: '../index/index'
            })
          }, 2000) //延迟时间 
        }
      })
    }, 20000);
  },
  //提交到服务器
  okClick(codeBase64, width) {
    var that = this;
    this.start()
    wx.request({
      // url: app.globalData.the_host + '/newcode/api/scan2.htm',
      url: app.globalData.the_host +`/fcode/decode`,
      data: {
        "code": codeBase64,
        "width": width,
        "isJPG": 0,
      },
      header: {
        'content-type': 'application/json'
      },
      method: "POST",
      success: res => {
        if (res.statusCode == 200) {
          console.log(res.data)
          that.stop()
          if (that.data.state==false){
            if (res.data.status == 0 || res.data.status == 30) {
              that.onstop();
              that.setData({
                isFlag: true,
                state:true,
                yfyindex: this.data.yfyindex + 1,
                msg: res.data.message
              })
              wx.showToast({
                title: res.data.message,
                icon: 'success',
                duration: 2000
              })
              const innerAudioContext = wx.createInnerAudioContext()
              innerAudioContext.autoplay = true
              innerAudioContext.src = app.globalData.the_host + '/image/sound/5383.mp3'
              innerAudioContext.onPlay(() => {
                console.log('开始播放')
              })
              innerAudioContext.onError((res) => {
                console.log(res.errMsg)
                console.log(res.errCode)
              })
              innerAudioContext.onEnded((res1) => {
                console.log('播放结束!');
                // let code1 = JSON.stringify(res.data.data)
                this.setData({
                  millisecond1: res.data.elapsedTime,
                })
                //let code = JSON.stringify(res.data.data)
                // console.log(code)//navigateBack
                clearInterval(intetimes);
                if (res.data.status==30){
                  wx.redirectTo({
                    url: '../tips/index?status=30&fcode=1&vcode=1'
                  })
                }else{
                  wx.redirectTo({
                    url: '../tips/index?fcode=' + res.data.data.fcode + "&vcode=" + res.data.data.vcode
                  })
                }
                
              })
            } else {
              that.setData({
                millisecond1: res.data.elapsedTime,
                msg: res.data.message
              })
              this.setData({
                isFlag: true
              })
            }
          }
        } else {
         
          this.stop()
          this.setData({
            titlename: res.data.message
          })
          wx.showToast({
            title: res.data.message,
            icon: 'success',
            duration: 2000
          })
        }
        // app.globalData.canuse = true
      }
    })
  },
  creatCanvas() {
    if (this.data.ctxCanvasNode !== '') return;
    let ctx = wx.createCanvasContext('scannerCanvas2');
    this.setData({
      ctxCanvasNode: ctx
    })

  },
  reloadCan() {
    wx.canvasToTempFilePath({
      canvasId: 'scannerCanvas2',
      fileType: 'jpg',
      quality: 1,
      success: (res) => {
        console.log('运行4')
        this.commit(res.tempFilePath);
        getApp().globalData.cameraTempImg = res.tempFilePath
      },
      fail: (e) => {
        console.log('运行5', e)
        this.reloadCan()

      }
    }, this)
  },


  error(e) {
    console.log(e.detai, 717)
  },
  
  //开始播放音乐---------------------------------------------------------------------------------------------
  onstart: function () {
   
    myaudio.play();
    console.log(myaudio.duration);
    this.setData({ isplay: true });

  },
  //停止播放
  onstop: function () {
    console.log('播放结束!12')
    myaudio.stop();
    this.setData({ isplay: false });
  },
  //-----------------计时器--------------------
  //开始
  start: function () {
    clearInterval(init);
    var that = this;
    that.setData({
      millisecond: 0,
      millisecond1: 0
    })
    init = setInterval(function () {
      that.timer()
    }, 50);
  },
  //暂停
  stop: function () {
    clearInterval(init);
  },
  //执行时间
  timer: function () {
    var that = this;
    //console.log(that.data.millisecond)
    that.setData({
      millisecond: that.data.millisecond + 50
    })
  },


})